<!doctype html>



  


<html class="theme-next mist use-motion">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />












  
  
  <link href="/vendors/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/vendors/font-awesome/css/font-awesome.min.css?v=4.4.0" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.0.1" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="Socket,Java," />








  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.0.1" />






<meta name="description" content="说明：Java Socket网络编程：java.net.ServerSocket/Socket/InetSocket/…">
<meta name="keywords" content="Socket,Java">
<meta property="og:type" content="article">
<meta property="og:title" content="Java 网络编程">
<meta property="og:url" content="http://bebetter.site/2017/09/01/Language/Java-advanced/Java 网络编程/index.html">
<meta property="og:site_name" content="gatewayzy">
<meta property="og:description" content="说明：Java Socket网络编程：java.net.ServerSocket/Socket/InetSocket/…">
<meta property="og:updated_time" content="2017-09-01T05:58:10.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Java 网络编程">
<meta name="twitter:description" content="说明：Java Socket网络编程：java.net.ServerSocket/Socket/InetSocket/…">



<script type="text/javascript" id="hexo.configuration">
  var NexT = window.NexT || {};
  var CONFIG = {
    scheme: 'Mist',
    sidebar: {"position":"right","display":"always"},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: 0,
      author: '博主'
    }
  };
</script>




  <link rel="canonical" href="http://bebetter.site/2017/09/01/Language/Java-advanced/Java 网络编程/"/>

  <title> Java 网络编程 | gatewayzy </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  










  
  
    
  

  <div class="container one-collumn sidebar-position-right page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-meta ">
  

  <div class="custom-logo-site-title">
    <a href="/"  class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <span class="site-title">gatewayzy</span>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>
  <p class="site-subtitle">blog of gatewayzy</p>
</div>

<div class="site-nav-toggle">
  <button>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
  </button>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      

      
    </ul>
  

  
</nav>

 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  
  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                Java 网络编程
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            <span class="post-meta-item-icon">
              <i class="fa fa-calendar-o"></i>
            </span>
            <span class="post-meta-item-text">发表于</span>
            <time itemprop="dateCreated" datetime="2017-09-01T13:58:10+08:00" content="2017-09-01">
              2017-09-01
            </time>
          </span>

          
            <span class="post-category" >
              &nbsp; | &nbsp;
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
              
                <span itemprop="about" itemscope itemtype="https://schema.org/Thing">
                  <a href="/categories/Language/" itemprop="url" rel="index">
                    <span itemprop="name">Language</span>
                  </a>
                </span>

                
                

              
            </span>
          

          
            
          

          

          
          

          
        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <p><strong>说明：</strong>Java Socket网络编程：java.net.ServerSocket/Socket/InetSocket/…<br><a id="more"></a></p>
<p>参考文章：</p>
<h2 id="Java-网络编程"><a href="#Java-网络编程" class="headerlink" title="Java 网络编程"></a>Java 网络编程</h2><ul>
<li>Socket属于TCP、UDP等抽象封装，不是一个协议。</li>
<li>socket常用类型：<code>SOCK_STREAM</code>(支持tcp)、<code>SOCK_DGRAM</code>(支持udp)。</li>
<li>Socket实现TCP连接过程：三次握手、数据传输、四次挥手。</li>
<li>更多的详细的网络知识看计算机网络。</li>
</ul>
<h2 id="ServerSocket"><a href="#ServerSocket" class="headerlink" title="ServerSocket"></a>ServerSocket</h2><ul>
<li>java.net.ServerSocket 用于服务器listen</li>
<li>java.net.Socket 用于client和server之间具体连接和数据传输</li>
<li>java.net.InetAddress 表示网络协议地址</li>
<li>java.io.DataInputStream/DataOutputStream 用于client与server读写数据</li>
</ul>
<h2 id="Java用socket实现C-S示例demo"><a href="#Java用socket实现C-S示例demo" class="headerlink" title="Java用socket实现C/S示例demo"></a>Java用socket实现C/S示例demo</h2><ul>
<li><p>ServerSocket.java：</p>
<ul>
<li>服务器启动一个ServerSocket类进行listen请求</li>
<li>accept()接收一个client的连接，如果setSoTimeout(10000)时间内没有新的连接会报异常</li>
<li>每次新accept一个socket连接，建立一个新的线程处理请求<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div></pre></td><td class="code"><pre><div class="line">package javaAdvanced;</div><div class="line"></div><div class="line">import java.io.DataInputStream;</div><div class="line">import java.io.DataOutputStream;</div><div class="line">import java.io.IOException;</div><div class="line">import java.net.InetAddress;</div><div class="line">import java.net.ServerSocket;</div><div class="line">import java.net.Socket;</div><div class="line"></div><div class="line">/**</div><div class="line"> * Created by dell on 2017/9/7.</div><div class="line"> */</div><div class="line">public class _03ServerSocket &#123;</div><div class="line"></div><div class="line">    public static void main(String[] args) throws Exception &#123;</div><div class="line">        InetAddress inetAddress = InetAddress.getLoopbackAddress();</div><div class="line">        ServerSocket serverSocket = new ServerSocket(8080, 50, inetAddress);</div><div class="line">        serverSocket.setSoTimeout(10000);  // 不设置的话会一直阻塞等待连接，这里设置超时关闭</div><div class="line">        System.out.println(&quot;=== serverSocket 需要一直处于监听状态：&quot;);</div><div class="line">        System.out.println(serverSocket.getInetAddress() + &quot;\t&quot; + serverSocket.getLocalPort());</div><div class="line">        while (true) &#123;</div><div class="line">            try &#123;</div><div class="line">                // 默认阻塞等待连接，如果用setSoTimeout设置超时限制，必须在时限内收到连接请求，否则超时异常</div><div class="line">                Socket socket = serverSocket.accept();</div><div class="line">                new Thread(() -&gt; &#123;</div><div class="line">                    try &#123;</div><div class="line">                        // 获取输入流，并读取内容</div><div class="line">                        DataInputStream dataInputStream = new DataInputStream(socket.getInputStream());</div><div class="line">                        System.out.println(dataInputStream.readUTF());</div><div class="line"></div><div class="line">                        // 获取输出流，向client发送消息</div><div class="line">                        DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream());</div><div class="line">                        dataOutputStream.writeUTF(String.format(&quot;【msg from server：%s】client你好~~&quot;, socket.getLocalAddress().toString()));</div><div class="line"></div><div class="line">                        // 关闭资源</div><div class="line">                        socket.close();</div><div class="line">                    &#125; catch (Exception e) &#123;</div><div class="line">                        e.printStackTrace();</div><div class="line">                    &#125;</div><div class="line">                &#125;).run();</div><div class="line">            &#125; catch (IOException e) &#123;</div><div class="line">                System.err.println(&quot;Accept timed out. 时限内没有收到连接请求...&quot;);</div><div class="line">            &#125;</div><div class="line">        &#125; // end of while</div><div class="line">        // serverSocket.close();</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
</li>
</ul>
</li>
<li><p>Client用Socket连接服务器示例：</p>
<ul>
<li>客户端确定server的地址InetAddress和port</li>
<li>新建一个socket连接服务器，client的地址和port默认是自动封装的，不用配置，socket默认是stream类型的</li>
<li>client与server使用java.io.DataInputStream/DataOutputStream相互通信<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div></pre></td><td class="code"><pre><div class="line">package javaAdvanced;</div><div class="line"></div><div class="line">import java.io.DataInputStream;</div><div class="line">import java.io.DataOutputStream;</div><div class="line">import java.io.InputStream;</div><div class="line">import java.io.OutputStream;</div><div class="line">import java.net.InetAddress;</div><div class="line">import java.net.Socket;</div><div class="line"></div><div class="line">/**</div><div class="line"> * Created by dell on 2017/9/7.</div><div class="line"> */</div><div class="line">public class _03ClientSocket &#123;</div><div class="line">    public static void main(String[] args) throws Exception &#123;</div><div class="line">        // 设置要连接的服务器的ip、port</div><div class="line">        int serverPort = 8080;</div><div class="line">        InetAddress inetAddress = InetAddress.getLoopbackAddress();</div><div class="line">        System.out.println(&quot;===准备连接服务器，服务器信息为：&quot;);</div><div class="line">        System.out.println(inetAddress.getHostAddress() + &quot;\t&quot; + serverPort);</div><div class="line">        // 建立一个client的socket，一般不设置client使用的ip、端口号，会自动封装</div><div class="line">        Socket socket = new Socket(inetAddress, serverPort);  // 默认使用stream类型，TCP。如果连接失败会立即抛出异常</div><div class="line">        System.out.println(&quot;=== Client使用的socket信息为：&quot;);</div><div class="line">        System.out.println(socket.getLocalAddress() + &quot;\t&quot; + socket.getLocalPort());</div><div class="line"></div><div class="line"></div><div class="line">        System.out.println(&quot;===连接服务器成功，服务器地址为：&quot; + socket.getRemoteSocketAddress());</div><div class="line">        // 获取输出流，并向server发送数据</div><div class="line">        OutputStream outputStream = socket.getOutputStream();</div><div class="line">        DataOutputStream dataOutputStream = new DataOutputStream(outputStream);</div><div class="line">        dataOutputStream.writeUTF(String.format(&quot;【msg from %s】Server你好，我是client！&quot;, socket.getLocalAddress().toString()));</div><div class="line">        // 获取输入流，读取server的数据</div><div class="line">        InputStream inputStream = socket.getInputStream();</div><div class="line">        DataInputStream dataInputStream = new DataInputStream(inputStream);</div><div class="line">        System.out.println(dataInputStream.readUTF());</div><div class="line"></div><div class="line">        // 关闭资源</div><div class="line">        socket.close();</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
</li>
</ul>
</li>
</ul>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Socket/" rel="tag">#Socket</a>
          
            <a href="/tags/Java/" rel="tag">#Java</a>
          
        </div>
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2017/09/01/Language/Java-advanced/Generic 泛型/" rel="next" title="Generic 泛型">
                <i class="fa fa-chevron-left"></i> Generic 泛型
              </a>
            
          </div>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2017/09/01/Language/Java-basic/Throwable 类及其继承体系/" rel="prev" title="Throwable 类及其继承体系">
                Throwable 类及其继承体系 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    


  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel ">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/statics/images/avatar.png"
               alt="gatewayzy" />
          <p class="site-author-name" itemprop="name">gatewayzy</p>
          <p class="site-description motion-element" itemprop="description">blog website with hexo and github pages</p>
        </div>
        <nav class="site-state motion-element">
          <div class="site-state-item site-state-posts">
            <a href="/archives">
              <span class="site-state-item-count">70</span>
              <span class="site-state-item-name">日志</span>
            </a>
          </div>

          
            <div class="site-state-item site-state-categories">
              <a href="/categories">
                <span class="site-state-item-count">10</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            <div class="site-state-item site-state-tags">
              <a href="/tags">
                <span class="site-state-item-count">38</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
        </div>

        
        

        
        
          <div class="links-of-blogroll motion-element links-of-blogroll-inline">
            <div class="links-of-blogroll-title">
              <i class="fa  fa-fw fa-globe"></i>
              友情链接
            </div>
            <ul class="links-of-blogroll-list">
              
                <li class="links-of-blogroll-item">
                  <a href="https://github.com/gatewayzy" title="Github-gatewayzy" target="_blank">Github-gatewayzy</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://google.com/" title="Goolge" target="_blank">Goolge</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://wiki.jikexueyuan.com/" title="Wiki-jike" target="_blank">Wiki-jike</a>
                </li>
              
            </ul>
          </div>
        

      </section>

      
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">
            
              
            
            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#Java-网络编程"><span class="nav-number">1.</span> <span class="nav-text">Java 网络编程</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#ServerSocket"><span class="nav-number">2.</span> <span class="nav-text">ServerSocket</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Java用socket实现C-S示例demo"><span class="nav-number">3.</span> <span class="nav-text">Java用socket实现C/S示例demo</span></a></li></ol></div>
            
          </div>
        </section>
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">gatewayzy</span>
</div>

<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Mist
  </a>
</div>

        

        
      </div>
    </footer>

    <div class="back-to-top">
      <i class="fa fa-arrow-up"></i>
    </div>
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  



  
  <script type="text/javascript" src="/vendors/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/vendors/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/vendors/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/vendors/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/vendors/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/vendors/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.0.1"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.0.1"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.0.1"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.0.1"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.0.1"></script>



  



  




  
  

  
  <script type="text/x-mathjax-config">
    MathJax.Hub.Config({
      tex2jax: {
        inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
        processEscapes: true,
        skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
      }
    });
  </script>

  <script type="text/x-mathjax-config">
    MathJax.Hub.Queue(function() {
      var all = MathJax.Hub.getAllJax(), i;
      for (i=0; i < all.length; i += 1) {
        all[i].SourceElement().parentNode.className += ' has-jax';
      }
    });
  </script>
  <script type="text/javascript" src="//cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>



  

  
<script type="text/javascript" async src="//push.zhanzhang.baidu.com/push.js">
</script>


</body>
</html>
